//
// Created by fys on 2020/5/14.
//

#include "common_ttcp.h"

size_t writen(int fd, void * buffer, size_t size)
{
    char* buffer_point = buffer;
    size_t length = size;

    while (length > 0)
    {
        size_t result = write(fd, buffer_point, length);
        if (result < 0)
        {
            if (errno == EINTR)
                continue;
            else
                return -1;
        }
        else if (result == 0)
        {
            return -1;
        }
        length = length - result;
        buffer_point = buffer_point + result;
    }
}

size_t readn(int fd, void* buffer, size_t size)
{
    char* buffer_pointer = buffer;
    size_t length = size;

    while (length > 0)
    {
        size_t result = read(fd, buffer_pointer, length);
        if (result < 0)
        {
            // Non-blocking condition
            if (errno == EINTR)
            {
                continue;
            }
            else
            {
                return (-1);
            }
        }
        // EOF(end if file)
        else if (result == 0)
        {
            printf("EOF\n");
            break;
        }
        length = length - result;
        buffer_pointer = buffer_pointer + result;
    }
    return (size - length);
}
